package com.laolu.icon.utils;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

@Slf4j
public class MyFileWrite implements AutoCloseable {
	private final BufferedWriter writer;
	
	public MyFileWrite(String filePath) throws IOException {
		this.writer = new BufferedWriter(new FileWriter(filePath));
	}
	
	public void newLine() throws IOException {
		writer.newLine();
	}
	
	public void writeString(String content) throws IOException {
		writer.write(content);
		writer.flush();
	}
	
	public void writeObject(Object o) throws IOException {
		String jsonString = JSONObject.toJSONString(o);
		writer.write(jsonString);
		writer.flush();
	}
	
	
	public void writeList(@NotNull List<?> list) {
		list.forEach(e -> {
			try {
				String jsonString = JSONObject.toJSONString(e);
				writer.write(jsonString);
				writer.newLine();
				writer.flush();
			} catch (IOException ex) {
				throw new RuntimeException(ex);
			}
		});
	}
	
	@Override
	public void close() throws Exception {
		writer.close();
	}
}
